#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string>
#include<cstring>

//只有一个比特位为1
#define ONE (1<<0)
#define TWO (1<<1)
#define THREE (1<<2)
#define FOUR (1<<3)


//code1
void PrintTest(int flags)
{
    if(flags & ONE)
	printf("one\n");
    if(flags & TWO)
	printf("two\n");
    if(flags & THREE)
	printf("three\n");
    if(flags & FOUR)
	printf("four\n");
}

void test1()
{

    printf("============================================\n");
    PrintTest(ONE);
    printf("============================================\n");
    PrintTest(TWO);
    printf("============================================\n");
    PrintTest(THREE);
    printf("============================================\n");
    PrintTest(ONE | TWO);
    printf("============================================\n");
    PrintTest(ONE | TWO | THREE);
    printf("============================================\n");
    PrintTest(ONE | TWO | FOUR);
    printf("============================================\n");
}

void test2()
{

   umask(0);
   //int fd1 = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666); // 覆盖原内容
   int fd1 = open("log.txt", O_WRONLY | O_CREAT | O_APPEND, 0666); //新增内容，追加
       if(fd1 < 0)
       {
	   perror("open");
	   errno = 1;
       }
       	printf("fd1:%d\n",fd1);
	
	const char* message = "hello world\n";
	write(fd1, message, strlen(message)); //所有的，这里的strlen不能+1，字符串以\0结尾是C语言的规定，与文件无关

	close(fd1);
}

void test3_std()
{
    const char* message = "hello stdout\n";
    write(1, message, strlen(message));  //证明了stdout的fd=1

    char buffer[128];
    size_t s = read(0, buffer, sizeof(buffer));
    if(s > 0)
    {
	buffer[s - 1] = 0;  //需要加上\0
	printf("%s\n",buffer);   // 证明了stdin的fd=1
    }


    //证明了FILE是结构体
    printf("stdin:%d\n",stdin->_fileno);
    printf("stdout:%d\n",stdout->_fileno);
    printf("stderr:%d\n",stderr->_fileno);
    FILE* fp = fopen("log,txt","w");
    printf("fp:%d\n",fp->_fileno);

}

void test4_int()
{
    int a = 12345;
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "%d",a);
    write(1, buffer, strlen(buffer));
}

void test5_stdout()
{
    int fd = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);//O_TRUNC输出重定向，O_APPEND追加重定向

    dup2(fd, 1);

    write(1, "hello 1\n", 8);

    printf("hello fd:%d\n", fd);
    fprintf(stdout, "hello fd:%d\n", fd);
    fputs("hello fputs\n", stdout);

    const char* message = "hello fwrite\n";
    fwrite(message, 1 ,strlen(message), stdout);
}
void test6_stdin()
{
    int fd = open("log.txt",O_RDONLY);
    dup2(fd, 0);  //输入重定向

    char buffer[2048];
    size_t s = read(0, buffer, sizeof(buffer));
    if(s > 0)
    {
	buffer[s] = 0;
	printf("stdin redir:\n%s\n");
    }
}
int main()
{
    //test1();
    //test2();
    //test3_std();
    //test4_int();
    //test5_stdout();
    test6_stdin();
   return 0;
}
